<template>
  <view class="container">
    <div class="basic-info">
      <!-- 车辆信息 -->
      <CarInfo :dict="dictEnums" :info="orderDetail.car_info" />
      <div class="gap"></div>
      <div>
        取车方式：<span class="custom-tag">{{ pickUpCarTypeName }}</span>
      </div>
      <div class="gap"></div>
      <!-- 租期信息 -->
      <LeaseInfo
        :info="orderDetail"
        :pickUpCarType="pickUpCarType"
        :pickUpCarTypeName="pickUpCarTypeName"
      />
    </div>
    <!-- 司机信息 -->
    <u-form :model="form" ref="uForm" label-width="230">
      <Card title="用车人信息">
        <div class="driver-info">
          <u-form-item label="服务商订单号" prop="refOrderCode">
            <u-input
              v-if="form.refOrderCode"
              input-align="right"
              :custom-style="{ color: '#a1a1a1' }"
              disabled
              v-model="form.refOrderCode"
            />
            <template v-else>
              <u-input
                input-align="right"
                :custom-style="{ color: '#a1a1a1' }"
                disabled
                value="暂无"
              />
            </template>
          </u-form-item>
          <u-form-item label="姓名" prop="driverName" required>
            <u-input
              input-align="right"
              ref="driverNameRef"
              :clearable="false"
              placeholder="请输入姓名"
              v-model="form.driverName"
            />
            <view
              v-if="form.driverName"
              class="clear-icon"
              @click="onClear('driverName')"
            >
              <u-icon size="32" name="close-circle-fill" color="#c0c4cc" />
            </view>
          </u-form-item>
          <u-form-item label="电话" prop="driverPhone" required>
            <u-input
              input-align="right"
              ref="driverPhoneRef"
              :clearable="false"
              placeholder="请输入电话"
              v-model="form.driverPhone"
            />
            <view
              v-if="form.driverPhone"
              class="clear-icon"
              @click="onClear('driverPhone')"
            >
              <u-icon size="32" name="close-circle-fill" color="#c0c4cc" />
            </view>
          </u-form-item>
          <u-form-item label="身份证号" prop="driverCredentialNo" required>
            <u-input
              input-align="right"
              ref="driverCredentialNoRef"
              :clearable="false"
              placeholder="请输入身份证号"
              v-model="form.driverCredentialNo"
            />
            <view
              v-if="form.driverCredentialNo"
              class="clear-icon"
              @click="onClear('driverCredentialNo')"
            >
              <u-icon size="32" name="close-circle-fill" color="#c0c4cc" />
            </view>
          </u-form-item>
        </div>
      </Card>
      <!-- 联系人信息 -->
      <Card title="联系人信息">
        <div class="driver-info">
          <u-form-item label="姓名" prop="contactName" required>
            <u-input
              input-align="right"
              :clearable="false"
              v-model="form.contactName"
              placeholder="请输入姓名"
            />
            <view
              v-if="form.contactName"
              class="clear-icon"
              @click="onClear('contactName')"
            >
              <u-icon size="32" name="close-circle-fill" color="#c0c4cc" />
            </view>
          </u-form-item>
          <u-form-item label="电话" prop="contactPhone" required>
            <u-input
              input-align="right"
              :clearable="false"
              v-model="form.contactPhone"
              placeholder="请输入电话"
            />
            <view
              v-if="form.contactPhone"
              class="clear-icon"
              @click="onClear('contactPhone')"
            >
              <u-icon size="32" name="close-circle-fill" color="#c0c4cc" />
            </view>
          </u-form-item>
          <u-form-item label="身份证号" prop="contactCredentialNo" required>
            <u-input
              input-align="right"
              :clearable="false"
              v-model="form.contactCredentialNo"
              placeholder="请输入身份证号"
            />
            <view
              v-if="form.contactCredentialNo"
              class="clear-icon"
              @click="onClear('contactCredentialNo')"
            >
              <u-icon size="32" name="close-circle-fill" color="#c0c4cc" />
            </view>
          </u-form-item>
        </div>
      </Card>
    </u-form>
    <!-- 门店信息 -->
    <StoreInfo :dict="dictEnums" :info="orderDetail.pick_up_store" />
    <!-- 供应商信息 -->
    <SupplierInfo :dict="dictEnums" :info="orderDetail.supplier_info" />
    <!-- 取消政策 -->
    <CancelRule
      :dict="dictEnums"
      :car_use_time="orderDetail.car_use_time"
      :info="orderDetail.cancel_strategy_struct"
    />
    <!-- 增值服务 -->
    <AddService :dict="dictEnums" :info="orderDetail.added_service_list" />
    <!-- 底部按钮 可用状态展示 -->
    <bottom-box>
      <view class="payment-block">
        <view class="price">
          <text class="label">订单金额：</text>
          <text class="icon">¥</text>
          <text class="num">{{ sumFee }}</text>
        </view>
        <view class="n-price-detail" @click="onExpenseDetailClick">
          <view>明细</view>
          <u-icon name="arrow-up" color="#2F86F6" size="18"></u-icon>
        </view>
        <view
          class="btn"
          @click="onConfirmClick"
          :class="{ disabled: okLoading }"
        >
          <u-loading
            v-if="okLoading"
            mode="flower"
            style="margin-right: 5px"
            size="40"
          ></u-loading>
          <text>确认下单</text>
        </view>
      </view>
    </bottom-box>
    <!-- 费用明细 -->
    <expenseDetails ref="expenseRef" :info="orderDetail"></expenseDetails>
    <!-- toast -->
    <u-toast ref="uToast" />
  </view>
</template>
<script>
import BottomBox from "@/components/bottom-box/bottom-box.vue";
import StoreInfo from "./compnoents/itemDetail/storeInfo.vue";
import CarInfo from "./compnoents/itemDetail/carInfo.vue";
import LeaseInfo from "./compnoents/itemDetail/leaseInfo.vue";
import DescriptionsItem from "./compnoents/itemDetail/descriptionsItem.vue";
import SupplierInfo from "./compnoents/itemDetail/supplierInfo.vue";
import CancelRule from "./compnoents/itemDetail/cancelRule.vue";
import AddService from "./compnoents/itemDetail/addService.vue";
import ExpenseDetails from "./compnoents/itemDetail/expenseDetails.vue";
import Card from "./compnoents/itemDetail/card.vue";
import {
  getEnums,
  priceTtemDetail,
  orderCreateCheck,
  orderCreate,
  currentUserStaff,
} from "@/api/user";
import decimal from "@/utils/calculation.js";

export default {
  data() {
    return {
      okLoading: false,
      // 商品 id
      itemsId: null,
      // 取车方式
      pickUpCarType: "",
      pickUpCarTypeName: "",
      orderDetail: {
        price_info: {},
        pick_up_store: {},
        pick_up_info: {},
        return_info: {},
        return_store: {},
      },
      dictEnums: {},
      form: {},
      rules: {
        driverName: [
          { required: true, message: "请输入姓名", trigger: "change" },
        ],
        driverPhone: [
          { required: true, message: "请输入电话", trigger: "change" },
        ],
        driverCredentialNo: [
          { required: true, message: "请输入身份证号", trigger: "change" },
          { len: 18, message: "身份证号长度应为18位", trigger: "change" },
        ],
        contactName: [
          { required: true, message: "请输入姓名", trigger: "change" },
        ],
        contactPhone: [
          { required: true, message: "请输入电话", trigger: "change" },
        ],
        contactCredentialNo: [
          { required: true, message: "请输入身份证号", trigger: "change" },
          { len: 18, message: "身份证号长度应为18位", trigger: "change" },
        ],
      },
    };
  },
  components: {
    StoreInfo,
    CarInfo,
    LeaseInfo,
    DescriptionsItem,
    CancelRule,
    AddService,
    SupplierInfo,
    ExpenseDetails,
    Card,
  },
  created() {
    // 获取页面枚举
    getEnums().then((res) => {
      if (res.code == 200) {
        const result = res.result;
        this.dictEnums = result;
      }
    });
    // 读取缓存
    const queryParamCatch = uni.getStorageSync("queryParamCatch");
    // 设置 form 数据
    this.form.driverName = queryParamCatch.userName || "";
    this.form.driverPhone = queryParamCatch.userPhone || "";
    this.form.driverCredentialNo = queryParamCatch.userIdCard || "";
    this.form.refOrderId = queryParamCatch.orderId;
    this.form.refOrderCode = queryParamCatch.orderCode;
    // 订单类型
    this.form.refOrderType = queryParamCatch.refOrderType || 1;

    // 获取用户信息
    this.getCurrentUserInfo();
  },
  computed: {
    // 选中的增值服务费
    checkedAddedServiceList() {
      let added_service_list = this.orderDetail.added_service_list || [];
      return added_service_list.filter((item) => item.checked);
    },
    sumFee() {
      const totalFee = this.orderDetail.price_info.total_fee || 0;

      let sum = totalFee;
      // 增值服务费
      this.checkedAddedServiceList.forEach((item) => {
        sum = decimal.add(sum, item.service_price_amount || 0);
      });
      return Number(sum).toFixed(2);
    },
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad(options) {
    this.itemsId = decodeURIComponent(options.id);
    this.pickUpCarType = options.pickUpCarType;
    this.pickUpCarTypeName = options.pickUpCarTypeName;
    priceTtemDetail({ itemId: this.itemsId }).then((res) => {
      if (res.code == 200) {
        const result = res.result;
        this.orderDetail = result;
      }
    });
  },
  methods: {
    // 获取用户信息
    getCurrentUserInfo() {
      currentUserStaff().then((res) => {
        if (res.code == 200) {
          const result = res.result;
          this.form.contactName = result.realname || "";
          this.form.contactPhone = result.phone || "";
          this.form.contactCredentialNo = result.identityCard || "";
        }
      });
    },
    // 清空输入框
    onClear(valueKey) {
      this.form[valueKey] = "";
      this.$forceUpdate();
    },
    // 费用明细
    onExpenseDetailClick() {
      this.$refs.expenseRef.open();
    },
    /**
     * 根据18位身份证号提取出生年月日。
     *
     * @param {string} idNumber - 18位身份证号码
     * @returns {string | null} - 出生年月日，格式为YYYY-MM-DD，如果输入不符合要求则返回null
     */
    getBirthdateFromIDCard(idNumber) {
      // 检查身份证号码长度
      if (idNumber.length !== 18) {
        return null;
      }

      // 检查前17位是否都是数字
      if (!/^\d{17}/.test(idNumber)) {
        return null;
      }

      // 检查最后一位是否是数字或大写的 'X'，如果是小写 'x' 转换成大写
      let lastChar = idNumber.charAt(17);
      if (lastChar === 'x') {
        lastChar = lastChar.toUpperCase();
      }
      if (lastChar < '0' || lastChar > '9' && lastChar !== 'X') {
        return null;
      }

      // 提取出生日期字符串
      const birthStr = idNumber.substring(6, 14);
      // 检查出生年份是否合理（例如，不在未来或过远的过去）
      const year = parseInt(birthStr.slice(0, 4), 10);
      if (year < 1900 || year > new Date().getFullYear()) {
        return null;
      }
      
      // 格式化生日字符串
      const birthday = `${birthStr.slice(0, 4)}-${birthStr.slice(4, 6)}-${birthStr.slice(6, 8)}`;
      return birthday + " 00:00:00";
    },
    // 确认下单
    onConfirmClick() {
      if (!this.okLoading) {
        this.okLoading = true;
        this.$refs.uForm.validate(async (valid) => {
          if (valid) {
            console.log("验证通过");
            const priceInfo = this.orderDetail.price_info;
            // 选中的增值服务
            const sidList = this.checkedAddedServiceList.map(
              (item) => item.sid
            );
            const param = {
              itemId: this.itemsId,
              // 司机
              driverName: this.form.driverName,
              driverPhone: this.form.driverPhone,
              driverCredentialType: 0,
              driverCredentialNo: this.form.driverCredentialNo,
              driverBirthday: this.getBirthdateFromIDCard(
                this.form.driverCredentialNo
              ),
              // 联系人
              contactName: this.form.contactName,
              contactPhone: this.form.contactPhone,
              contactCredentialType: 0,
              contactCredentialNo: this.form.contactCredentialNo,
              contactBirthday: this.getBirthdateFromIDCard(
                this.form.contactCredentialNo
              ),

              // 选择的增值服务
              selectAddServices: sidList.join(","),
              totalAmount: this.sumFee,
              payAmount: this.sumFee,
              // 优惠政策
              promotionList: priceInfo.promotion_info
                ? [priceInfo.promotion_info]
                : [],
            };

            console.log("预下单param", param);
            orderCreateCheck(param).then((resCheck)=>{
              if (resCheck.code == 200) {
                this.$u.toast("预下单成功，正在下单...");
                const createParam = {
                  ...param,
                  refOrderId: this.form.refOrderId,
                  refOrderCode: this.form.refOrderCode,
                  refOrderType: this.form.refOrderType,
                };
                orderCreate(createParam).then((resCreate) => {
                  if (resCreate.code == 200) {
                    this.$refs.uToast.show({
                      title: "下单成功",
                      duration: 3000,
                      back: true,
                    });
                  } else {
                    this.okLoading = false
                  }
                }).catch(() => {
                  this.okLoading = false
                });
              } else {
                this.okLoading = false  
              }
            }).catch(() => {
              this.okLoading = false  
            });
          } else {
            this.okLoading = false
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #f9fafd;
  padding: 32rpx;
  .basic-info {
    position: relative;
    box-shadow: 0 4rpx 60rpx 0 rgba(201, 205, 216, 0.13);
    background: #fff;
    border-radius: 4rpx;
    padding: 32rpx;
  }
  .gap {
    height: 16rpx;
    width: 100%;
  }
}

::v-deep .ve-bottom-box-wrap {
  z-index: 99 !important;
}
::v-deep .ve-bottom-box-wrap-content {
  padding-top: 0 !important;
  padding-left: 0 !important;
  padding-right: 0 !important;
}
.payment-block {
  position: relative;
  box-shadow: 0 -20rpx 20rpx 0 rgba(209, 212, 223, 0.1);
  .num {
    color: #fc5042;
  }
  .priceInfo {
    white-space: nowrap;
    position: absolute;
    color: #909399;
    font-size: 22rpx;
    bottom: 0;
    left: 30rpx;
  }
  .n-price-detail {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    color: #2f86f6;
    font-size: 28rpx;
    top: 30rpx;
    left: 420rpx;
    view:nth-child(1) {
      margin-right: 12rpx;
    }
  }
}
.clear-icon {
  margin-top: 4px;
  margin-left: 6px;
}
.custom-tag {
  display: inline-block;
  font-size: 22rpx;
  margin-right: 12rpx;
  margin-bottom: 16rpx;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  border: 1rpx solid #2f86f6;
  color: #2f86f6;
  background-image: linear-gradient(to right, #1e72ff 0%, #42a1ff 100%);
  color: #ffffff;
}
.payment-block .btn.disabled {
  background: linear-gradient(315deg, #c6c9d5, #858a9f);
}
</style>
